﻿package game.network.api.fb.net{

	import flash.events.DataEvent;
	import flash.events.ErrorEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;

	public class FacebookRequest extends AbstractFacebookRequest {

		protected var fileReference:FileReference;

		public function FacebookRequest ():void {
			super ();
		}

		public function call (url:String, requestMethod:String = 'GET', callback:Function = null, values:* = null):void {

			_url = url;
			_requestMethod = requestMethod;
			_callback = callback;

			var requestUrl:String = url;

			urlRequest = new URLRequest(requestUrl);
			urlRequest.method = _requestMethod;

			if (values == null) {
				loadURLLoader ();
				return;
			}

			var fileData:Object = extractFileData(values);
			if (fileData == null) {
				urlRequest.data = objectToURLVariables(values);
				loadURLLoader ();
				return;
			}

			if (fileData is FileReference) {
				urlRequest.data = objectToURLVariables(values);
				urlRequest.method = URLRequestMethod.POST;

				fileReference = fileData as FileReference;
				fileReference.addEventListener ( DataEvent.UPLOAD_COMPLETE_DATA, handleFileReferenceData, false, 0, true );

				fileReference.addEventListener ( IOErrorEvent.IO_ERROR, handelFileReferenceError, false, 0, false );

				fileReference.addEventListener ( SecurityErrorEvent.SECURITY_ERROR, handelFileReferenceError, false, 0, false );

				fileReference.upload (urlRequest);
				return;
			}

			urlRequest.data = createUploadFileRequest(fileData,values).getPostData();
			urlRequest.method = URLRequestMethod.POST;

			loadURLLoader ();
		}

		override public function close ():void {
			super.close ();

			if (fileReference != null) {
				fileReference.removeEventListener ( DataEvent.UPLOAD_COMPLETE_DATA, handleFileReferenceData );

				fileReference.removeEventListener ( IOErrorEvent.IO_ERROR, handelFileReferenceError );

				fileReference.removeEventListener ( SecurityErrorEvent.SECURITY_ERROR, handelFileReferenceError );

				try {
					fileReference.cancel ();
				} catch (e:Error) {
					
				}

				fileReference = null;
			}
		}

		protected function handleFileReferenceData (event:DataEvent):void {
			handleDataLoad (event.data);
		}

		protected function handelFileReferenceError (event:ErrorEvent):void {
			_success = false;
			_data = event;

			dispatchComplete ();
		}

	}

}